package top.mybatisx.mpquery.query;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
import top.mybatisx.mpquery.service.MPQueryxService;
import top.mybatisx.sql.core.query.SqlWrapper;
import top.mybatisx.sql.core.sql.base.SqlStruct;

import java.util.List;
import java.util.Map;

/**
 * 查询包装类
 */
public class Db extends SqlWrapper implements BaseQueryxWrapper {

    private static Logger logger = LoggerFactory.getLogger(Db.class);

    // 单例模式
    private Db() {
    }

    public static Db create() {
        return new Db();
    }


    @Override
    public List<Map<String, Object>> list() {
        SqlStruct sqlStruct = this.buildSql();
        logger.info("\nsql------>{}\nparams--->{}", sqlStruct.getSql(), sqlStruct.getParams());
        List<Map<String, Object>> list = MPQueryxService.selectList(sqlStruct.getSql(), sqlStruct.getParams());
        return list;
    }

    public <E> List<E> list(Class<E> resultType) {
        SqlStruct sqlStruct = this.buildSql();
        logger.info("\nsql------>{}\nparams--->{}", sqlStruct.getSql(), sqlStruct.getParams());
        List<E> list = MPQueryxService.selectList(sqlStruct.getSql(), sqlStruct.getParams(), resultType);
        return list;
    }

    public Map<String, Object> one() {
        List<Map<String, Object>> list = this.list();
        Assert.isTrue(list.size() < 2, "one()查询数量大于1,请核对");
        if (list.size() == 0) {
            return null;
        }

        return list.get(0);
    }

    public <E> E one(Class<E> clazz) {
        List<E> list = this.list(clazz);
        Assert.isTrue(list.size() < 2, "one()查询数量大于1,请核对");
        if (list.size() == 0) {
            return null;
        }
        return list.get(0);
    }

}
